﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取本机的ip
            var hostName = Dns.GetHostName();
            var localhostIPs = Dns.GetHostByName(hostName);
            IPAddress IP = localhostIPs.AddressList[0];
            txtServer.Text = IP.ToString();

            //txtServer.Text = IPAddress.Any.ToString();

            Control.CheckForIllegalCrossThreadCalls = false;
        }

        #region 监听方法

        private Socket socketSend;

        //记录所有连入的客户端
        private Dictionary<string, Socket> distanceSocket = new Dictionary<string, Socket>();

        private void Listen(object o)
        {
            Socket socketWatch = o as Socket;

            while (true)
            {
                //监听
                try
                {
                    //负责跟客房端通信
                    socketSend = socketWatch.Accept();

                    //将远程连接的客户端的IP地址和Socket存入集合中
                    distanceSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);

                    //将远程连接客户的IP加入下拉框
                    cbxUsers.Items.Add(socketSend.RemoteEndPoint.ToString());
                    //自动选择到新连入的客户端
                    cbxUsers.SelectedIndex = cbxUsers.Items.IndexOf(socketSend.RemoteEndPoint.ToString());

                    ShowMessage(socketSend.RemoteEndPoint.ToString() + "：连接成功！");

                    //开新的线程不停的接受客户端发送的信息
                    Thread th = new Thread(Receive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
                catch
                {
                    MessageBox.Show("网络连接错误，请重新连入！");
                }
            }
        }

        /// <summary>
        /// 服务端不停的接受客户端发送来的消息
        /// </summary>
        /// <param name="o"></param>
        private void Receive(object o)
        {
            //转换传入的参数类型
            Socket socketSend = o as Socket;

            //用循环持续接收二进制消息，指导消息读取完毕
            while (true)
            {
                // 每2M为一次读取单位
                byte[] buffer = new byte[1024 * 1024 * 5];
                //实际接收的有效字节数
                int r = socketSend.Receive(buffer);
                //指导字节读取完成，跳出循环
                if (r == 0)
                    break;

                //把二进制内容转换为字符串
                var str = Encoding.UTF8.GetString(buffer, 0, r);
                ShowMessage(socketSend.RemoteEndPoint + "：" + str);
            }
        }

        #endregion 监听方法

        private void ShowMessage(string msgStr)
        {
            txtLog.AppendText(msgStr + "\r\n");
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            try
            {
                //当点击开始监听时，在服务器端创建一个负责监听的IP地址和端口号
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                //创建端口号对象
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));

                //开始监听
                socketWatch.Bind(point);
                ShowMessage("监听成功...");
                socketWatch.Listen(10);

                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWatch);
            }
            catch
            {
                MessageBox.Show("网络连接错误，请重新连入！");
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text;
            //把消息转换为二进制
            byte[] buffer = Encoding.UTF8.GetBytes(str);

            List<byte> list = new List<byte>();
            list.Add(0);
            list.AddRange(buffer);

            //生成新的二进制数组
            byte[] newBuffer = list.ToArray();

            //获得要发送客户端的IP
            string IP = cbxUsers.SelectedItem.ToString();

            if (string.IsNullOrEmpty(IP))
            {
                MessageBox.Show("请先选择客户端!");
                return;
            }

            distanceSocket[IP].Send(newBuffer);
        }

        private void btnShake_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1];
            buffer[0] = 2;
            distanceSocket[cbxUsers.SelectedItem.ToString()].Send(buffer);
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();
            //对话框的配置
            dialog.InitialDirectory = @"c:\AAA";
            dialog.Title = "请选择要发送的文件";
            dialog.Filter = "所有文件|*.*";
            dialog.ShowDialog();

            txtPath.Text = dialog.FileName;
        }

        private void btnPhoto_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtPath.Text))
            {
                MessageBox.Show("请选择文件！");
                return;
            }

            var path = txtPath.Text.Trim();
            //请取文件内容，进行发送
            using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 5];
                int r = fsRead.Read(buffer, 0, buffer.Length);

                //文件数据前加一个类型数据
                List<byte> list = new List<byte>();
                list.Add(1);
                list.AddRange(buffer);
                byte[] newBuffer = list.ToArray();

                //把处理好的二进制数组发送给客户端
                distanceSocket[cbxUsers.SelectedItem.ToString()].Send(newBuffer, 0, r + 1, SocketFlags.None);
            }

        }
    }
}
